import React, {useEffect, useState} from 'react';
import './index.css';

import {Layout, Menu} from 'antd';
import {withRouter} from 'react-router-dom';
import axios from 'axios';
import {
  BarsOutlined,
  HomeOutlined,
  SafetyOutlined,
  ToolOutlined,
  UserOutlined,
  WomanOutlined,
} from '@ant-design/icons';

const {Sider} = Layout;
const {Item, SubMenu} = Menu;

const iconList = {
  '/home': <HomeOutlined/>,
  '/user': <UserOutlined/>,
  '/user/list': <BarsOutlined/>,
  '/role_power': <SafetyOutlined/>,
  '/role_power/role/list': <WomanOutlined/>,
  '/role_power/power/list': <ToolOutlined/>,
}

/**
 * 左侧菜单组件
 */
function LeftMenu(props) {
  /* 是否收起左侧菜单栏 */
  const [collapsed] = useState(false);
  /* 是否收起左侧菜单栏 */
  const [menuList,setMenuList] = useState([]);

  useEffect(()=>{
    // 获取左侧菜单列表，放入menuList中
    axios.get("http://localhost:5000/rights?_embed=children").then(r => {
      console.log("menuList",r.data);
      setMenuList(r.data);
    })
  },[]);

  /**
   * 初始化左侧菜单
   * menuList 菜单列表
   */
  const readerMenu = (menuList)=>{
    // 判断是否是一级菜单，如果不是一级菜单则递归
    return menuList.map((menu)=>{
      if (menu.children && menu.pagepermisson === 1 && menu.children.length > 0) {
        return (
          <SubMenu key={menu.key} icon={iconList[menu.key]} title={menu.title}>
            {readerMenu(menu.children)}
          </SubMenu>
        )
      }else {
        return (
          menu.pagepermisson === 1 && <Item key={menu.key} icon={iconList[menu.key]} onClick={()=>{
            // 点击某个子菜单的时候跳转路由
            props.history.push(menu.key);
          }}>
            {menu.title}
          </Item>
        )
      }
    });
  }

  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <div className="logo">全球新闻发布系统</div>
      <Menu theme="dark" mode="inline" defaultSelectedKeys={['/home']}>
        {readerMenu(menuList)}
      </Menu>
    </Sider>
  );
}

export default withRouter(LeftMenu);